/**
 * <b>项目名：</b>hclv-web<br/>  
 * <b>包名：</b>com.flea.hclv.service.impl<br/>  
 * <b>文件名：</b>HHotelServiceImpl.java<br/>  
 * <b>版本信息：</b>1.0<br/>  
 * <b>日期：</b>2018年9月12日 下午3:50:38<br/>  
 * <b>COPYRIGHT 2010-2012 ALL RIGHTS RESERVED 虫子科技</b>-版权所有<br/>
 */
package com.flea.hclv.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.flea.hclv.model.dao.HLineMapper;
import com.flea.hclv.model.entity.HLine;
import com.flea.hclv.model.entity.HSpot;
import com.flea.hclv.model.entity.HlineSpotRelation;
import com.flea.hclv.service.HLineService;
import com.flea.hclv.service.HLineSpotRelationService;
import com.flea.hclv.util.ServerResponse;
import com.flea.system.base.util.StringUtil;
import com.flea.system.bean.FleaPage;
import com.flea.system.platform.session.FleaOrgUtils;
import com.flea.system.utils.FleaStringUtils;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @description
 * @createTime 2018年9月12日 下午3:50:38
 * @modifyTime
 * @author myflea@163.com
 * @version 1.0
 */
@Service("lineService")
public class HLineServiceImpl implements HLineService {
	@Autowired
	private HLineMapper lineMapper;

	@Autowired
	private HLineSpotRelationService lineSpotRelationService;

	@Override
	public FleaPage<HLine> findForGird(int curPage, int pageSize, String name, String type, String deptId) {
		RowBounds rowBounds = new RowBounds(curPage, pageSize);
		List<HLine> pageData = lineMapper.selectPagings(rowBounds, name, type, deptId);

		FleaPage<HLine> result = new FleaPage<>(pageData);
		List<HLine> lines = converUserCodeToName(pageData);
    result.setCurPageData(lines);
				return result;
	}

  private List<HLine> converUserCodeToName(List<HLine> pageData) {
	  List<HLine> result = new ArrayList<>();
    for (HLine line:pageData
    ) {
      line.setCreateUserName(FleaOrgUtils.getUserNameByUserUuid(line.getCreateUser()));
      result.add(line);
    }
	  return result;
  }

  @Override
	public List<HLine> queryAll(String deptId, String type) {
		return lineMapper.selectAll(deptId, type);
	}

	@Override
	public HLine queryById(String id) {
		HLine hLine = lineMapper.selectByPrimaryKey(id);
		return hLine;
	}

	@Override
	public boolean save(HLine entity, String spots) throws Exception {
		if (StringUtil.isEmpty(entity.getId())) {
			entity.setId(FleaStringUtils.getGenerateUUID());
		}
		int result = lineMapper.insert(entity);
		if (result <= 0) {
			throw new Exception("线路插入失败！");
		}
		List<HSpot> list = JSON.parseArray(spots, HSpot.class);
		List<String> spotIdList = Lists.newArrayList();
		if (CollectionUtils.isNotEmpty(list)){
			for(HSpot spot : list){
				spotIdList.add(spot.getId());
			}
		}
//		if (spotIdList.size() == 0)
//			return result > 0;
    if(spotIdList.size() == 0){
      return true;
    }
		return saveRelation(spotIdList, entity.getId(), entity.getCreateUser());
		/*
		 * List<HlineSpotRelation> lineSpotRelationList = new ArrayList<>();
		 * HlineSpotRelation lineSpotRelation = null; String lineId = entity.getId();
		 * String userId = entity.getCreateUser(); for(int i = 0; i < spotList.size();
		 * i++) { lineSpotRelation = new HlineSpotRelation();
		 * lineSpotRelation.setId(FleaStringUtils.getGenerateUUID());
		 * lineSpotRelation.setLineId(lineId);
		 * lineSpotRelation.setSpotId(spotList.get(i)); lineSpotRelation.setSerial(i+1);
		 * lineSpotRelation.setCreateUser(userId);
		 * lineSpotRelationList.add(lineSpotRelation); } return
		 * lineSpotRelationService.save(lineSpotRelationList);
		 */
	}

	public boolean saveRelation(List<String> spotList, String lineId, String userId) throws Exception {
		List<HlineSpotRelation> lineSpotRelationList = new ArrayList<>();
		HlineSpotRelation lineSpotRelation = null;
		for (int i = 0; i < spotList.size(); i++) {
			lineSpotRelation = new HlineSpotRelation();
			lineSpotRelation.setId(FleaStringUtils.getGenerateUUID());
			lineSpotRelation.setLineId(lineId);
			lineSpotRelation.setSpotId(spotList.get(i));
			lineSpotRelation.setSerial(i + 1);
			lineSpotRelation.setCreateUser(userId);
			lineSpotRelationList.add(lineSpotRelation);
		}
		return lineSpotRelationService.save(lineSpotRelationList);
	}

	@Override
	public boolean update(HLine entity, String lines) throws Exception {
		if (StringUtil.isEmpty(entity.getId())) {
			throw new Exception("缺少id");
		}
		HLine hLine = this.queryById(entity.getId());
		if (!StringUtil.isEmpty(entity.getName())) {
			hLine.setName(entity.getName());
		}
		if (!StringUtil.isEmpty(entity.getDescription())) {
			hLine.setDescription(entity.getDescription());
		}
		if (!StringUtil.isEmpty(entity.getType())) {
			hLine.setType(entity.getType());
		}
		if (!StringUtil.isEmpty(entity.getStatus())) {
			hLine.setStatus(entity.getStatus());
		}
		if (!StringUtil.isEmpty(entity.getValid())) {
			hLine.setValid(entity.getValid());
		}
		if (!StringUtil.isEmpty(entity.getModifyUser())) {
			hLine.setModifyUser(entity.getModifyUser());
		}
		int result = lineMapper.updateByPrimaryKey(hLine);
		if (result <= 0) {
			throw new Exception("线路插入失败！");
		}

		List<String> spotList = JSON.parseArray(lines, String.class);

		if (spotList.size() == 0)
			return result > 0;
		return saveRelation(spotList, entity.getId(), entity.getCreateUser());
	}

	@Override
	public boolean delete(String ids, String userId) throws Exception {
		List<String> idsArray = JSON.parseArray(ids, String.class);
		if (lineMapper.delete(idsArray) <= 0) {
			throw new Exception("线路删除失败！");
		}
		List<String> lineIds = new ArrayList<>();
		if (idsArray.size() == 1) {
			lineIds.add(idsArray.get(0));
		} else {
			lineIds.addAll(idsArray);
		}
		return lineSpotRelationService.deleteByLineId(JSON.toJSONString(lineIds), userId);
	}

  @Override
  public ServerResponse<HLine> updateInfo(HttpServletRequest request, String lineInfos) throws  Exception {
	  String userId = FleaOrgUtils.getCurUserUuid(request);
	  JSONObject paraJSON = JSONObject.parseObject(lineInfos);

	  if(null==paraJSON){
	    return ServerResponse.createByErrorMessage("传递的参数不合法");
    }
    HLine line = JSONObject.parseObject(String.valueOf(paraJSON.get("line")),HLine.class);
	  if(null==line || StringUtil.isEmpty(line.getId())){
	    return ServerResponse.createByErrorMessage("未能正确解析线路参数");
    }
    List<HSpot> spots = JSONObject.parseArray(String.valueOf(paraJSON.get("spots")),HSpot.class);

//	  if(null==spots || spots.size()==0){
//      return ServerResponse.createByErrorMessage("未获取到需要的景点相关数据，请检查");
//    }
    String lineId = line.getId();
	  //删除 与该线路相关联的 景点与线路相关联关系表
    lineSpotRelationService.deleteByLineId(lineId, userId);
    boolean result =false;
   /* boolean result = lineSpotRelationService.deleteByLineId(lineId, userId);
    if(!result){
      throw new Exception("删除原线路景点关系失败");
    }*/
    //封装组合修改数据

    line.setModifyUser(userId);
    List<HlineSpotRelation> relations = new ArrayList<>();
    for (HSpot spot:spots) {
      HlineSpotRelation relation = new HlineSpotRelation();
      relation.setCreateUser(userId);
      relation.setSpotId(spot.getId());
      relation.setId(FleaStringUtils.getGenerateUUID());
      relation.setLineId(lineId);
      relation.setModifyUser(userId);
      relations.add(relation);
    }
    result = lineMapper.updateByPrimaryKey(line)==1;
    if(!result){
      throw new Exception("更新线路失败");
    }
    if(null!=relations && relations.size()>0){
      result = lineSpotRelationService.save(relations);
      if(!result){
        throw new Exception("更新线路与景点关系失败");
      }
    }

    return ServerResponse.createBySuccessMessage("线路更新成功");
  }
}
